<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\report;

use app\command\BaseWork;
use app\enum\ReportRecordEnum;
use app\model\PushReportRecordModel;
use app\model\ReportRecordPushModel;
use app\service\report\ReportPullService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;

class ReportRecordFileConsumerWork extends BaseWork
{
    public const REDIS_TASK_KEY = ReportRecordEnum::CONFIG_KEY['report_process_fetch'];

    protected function configure()
    {
        // 指令配置
        $this->setName('report_record_file_consumer_work');
        $this->setDescription('报表文件消费者')
            ->addArgument('id', Argument::OPTIONAL, 'id');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return void
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $redis = Cache::store('redis')->handler();
        $st = time() + 5 * 60;
        while (time() < $st) {
            $reportPullId = intval($redis->lPop(self::REDIS_TASK_KEY));
            if (! $reportPullId) {
                usleep(500000);
                continue;
            }
            try {
                $this->getOutputMessage('消费报表文件队列开始,id:' . $reportPullId);
                $items = ReportPullService::getPushReportRecordSend($reportPullId);
                if (! $items) {
                    $this->getOutputMessage('获取发送生成报表数据队列失败,报表id:' . $reportPullId . ReportPullService::getError(0));
                } else {
                    $redis->rPush(ReportRecordEnum::CACHE_CONFIG['report_send_fetch'], $reportPullId);
                    ReportPullService::setStatus($reportPullId, ReportRecordPushModel::STATUS_WAIT_SEND);
                }
                $this->getOutputMessage('消费报表文件队列结束,id:' . $reportPullId);
            } catch (\Exception $e) {
                $this->getOutputMessage('获取发送生成报表数据队列失败' . $e->getMessage());
            }
        }
        $this->getOutputMessage('获取发送生成报表数据队列结束');
    }
}
